import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xvideos/tools_base/debug_log.dart';

///倒计时
class ShortTimerCount extends StatefulWidget {
  final int seconds;
  final ValueChanged<int>? countdownValue;
  final VoidCallback? countdownEnd;
  final String? text;
  final TextStyle? t;
  final double? height;

  const ShortTimerCount({
    Key? key,
    this.seconds = 10,
    this.countdownEnd,
    this.countdownValue,
    this.t,
    this.text,
    this.height,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ShortTimerCountState();
  }
}

class _ShortTimerCountState extends State<ShortTimerCount> {
  late int _seconds;
  final List<InlineSpan> _widgetList = <InlineSpan>[];
  Timer? _timer;

  TextStyle get t1 => widget.t ?? const TextStyle(fontSize: 12, color: Colors.black);

  @override
  void initState() {
    super.initState();
    _seconds = widget.seconds;
    if (_seconds != 0) {
      initTimer();
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        _seconds--;
        widget.countdownValue?.call(_seconds);
        if (_seconds == -1) {
          _timer?.cancel();
          _timer = null;
          countdownEnd();
        } else {
          initTimer();
        }
      });
    }
  }

  void countdownEnd() {
    widget.countdownEnd?.call();
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _timer = null;
    debugLog("tag", "定时器销毁了-------------------------------------------");
  }

  initTimer() {
    var timer = constructTime(_seconds);
    _widgetList.clear();
    var text = WidgetSpan(
      child: Container(
        height: widget.height ?? 38,
        alignment: Alignment.center,
        decoration: BoxDecoration(color: Colors.transparent, borderRadius: BorderRadius.circular(2)),
        child: Text(
          timer,
          style: t1,
        ),
      ),
    );
    _widgetList.add(text);
    if (mounted) {
      setState(() {});
    }
  }

  get2Str(int data) {
    return data.toString().padLeft(2, "0");
  }

  String constructTime(int seconds) {
    // int day = seconds ~/ (3600 * 24);
    int hour = seconds % (3600 * 24) ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    return (widget.text ?? "") + get2Str(hour) + get2Str(minute) + get2Str(second);
  }

  @override
  Widget build(BuildContext context) {
    return RichText(text: TextSpan(children: _widgetList));
  }
}
